/**
 * Created by Administrator on 2017/1/16.
 */

var pomelo = require('pomelo');
var messageService = require('../messageService');

require('../../util/class');
exports.GamePlayer = Class.extend({
    _uid: 0,                     // uid
    _sid: null,                 // 前端服务器id

    _user: null,
    _gps: null,                 // 定位信息

    _room: null,                // 房间
    _index: 0,                  // 坐位号

    _online: false,            // 是否在线
    _ready: false,             // 是否准备
    _playing: false,          // 是否正在游戏
    _background: false,        // 是否在后台运行

    _marks: null,             // 状态标志

    _waitHandleTime: 0,       // 等待处理消息的开始时间
    _waitTimeoutTimer: 0,     // 等待定时器
    _waitTimeoutTime: 0,      // 等待定时器开始时间

    _trustee: 0,               // 托管状态, 0未托管 1手动托管 2自动托管
    _ai: null,                 // AI处理器

    _stat: null,              // 统计数据



    /**
     * 构造函数
     * @param uid 玩家uid
     * @param msg 消息参数
     */
    init: function(uid, msg) {
        this._uid = uid;
        this._sid = null;

        this._user = null;
        this._gps = null;
        this.initUser(msg);

        this._room = null;
        this._index = 0;

        this._online = true;
        this._ready = false;
        this._playing = false;
        this._background = false;

        this._waitHandleTime = 0;
        this._waitTimeoutTimer = 0;
        this._waitTimeoutTime = 0;

        this._trustee = 0;
        this._ai = null;

        this._marks = {};

        this._stat = {
            score: 0,                // 积分
            roundScore: 0,          // 本轮积分情况
            roundCoin: 0,           // 金币场专用
        }
    },

    /**
     * 初始化玩家信息
     * @param msg
     */
    initUser: function(msg) {
        this._user = msg.user;
        if (msg.gps) {
            this._gps = msg.gps;
        }
    },

    /**
     * 玩家uid
     * @returns {number}
     */
    uid: function() {
        return this._uid;
    },

    /**
     * 内部前端服务器编号，用于发送数据
     * @returns {number}
     */
    sid: function() {
        return this._sid;
    },

    getUserValue: function(key) {
        return this._user[key];
    },

    setUserValue: function(key, value, sync) {
        this._user[key] = value;

        if (sync) {
            if (key == "coin") {
                this.getRoom().broadcast("onGameSyncCoins", ExObject.build(this.uid(), value));
            } else {
                this.send("onPlayerSync", {
                    key: key,
                    value: value
                });
            }
        }
    },

    updateUser: function(user) {
        ExObject.each(user, function(k ,v) {
            if (!this._user.hasOwnProperty(k)) {
                return;
            }

            this._user[k] = v;

            if (k == "coin") {
                this.getRoom().broadcast("onGameSyncCoins", ExObject.build(this.uid(), v));
            } else {
                this.send("onPlayerSync", {
                    key: k,
                    value: v
                });
            }
        }.bind(this));
    },

    getResource: function(key) {
        return this._user[key] || 0;
    },

    checkResource: function(name, value) {
        if (ExObject.isObject(name)) {
            return ExObject.numberGTE(this._user, name);
        } else {
            return this.getResource(name) >= value;
        }
    },

    /**
     * 修改资源
     * @param key
     * @param value
     * @returns {number} 实际变化量
     */
    alterResource: function(key, value) {
        var old = this._user[key] || 0;
        this._user[key] = Math.max(0, old + value);
        return this._user[key] - old;
    },

    addResourceSync: function(name, value, reason) {
        var resource = null;
        if (ExObject.isObject(name)) {
            resource = name;
            reason = value;
        } else {
            resource = ExObject.build(name, value);
        }
        pomelo.app.rpc.world.userRemote.addResource(null, this.uid(), resource, reason||"gameAdd", function(resp) {
            if (resp.code) {
                return;
            }
            this.updateUser(resp.status);
        }.bind(this));
    },

    costResourceSync: function(name, value, reason) {
        var resource = null;
        if (ExObject.isObject(name)) {
            resource = name;
            reason = value;
        } else {
            resource = ExObject.build(name, value);
        }

        pomelo.app.rpc.world.userRemote.costResource(null, this.uid(), resource, reason||"gameCost", function(resp) {
            if (resp.code) {
                return;
            }
            this.updateUser(resp.status);
        }.bind(this));
    },

    alterResourceSync: function(name, value, reason) {
        var resource = null;
        if (ExObject.isObject(name)) {
            resource = name;
            reason = value;
        } else {
            resource = ExObject.build(name, value);
        }

        pomelo.app.rpc.world.userRemote.alterResource(null, this.uid(), resource, reason||"gameAlter", function(resp) {
            if (resp.code) {
                return;
            }
            this.updateUser(resp.status);
        }.bind(this));
    },

    /**
     * 是否是机器人
     * @returns {boolean}
     */
    isRobot: function() {
        return this._user.robot;
    },

    /**
     * 玩家名称
     * @returns {*}
     */
    getName: function() {
        return this._user.name;
    },

    /**
     * 玩家GM级别
     * @returns {number|*}
     */
    getGmLevel: function() {
        return this._user.gmLevel;
    },

    /**
     * 是否是超级管理员
     * @returns {boolean}
     */
    isSuperGM: function() {
        return this.getGmLevel() == Def.GM_LEVEL_SUPER;
    },

    /**
     * 获取所在房间
     * @returns {null}
     */
    getRoom: function() {
        return this._room;
    },

    /**
     * 设置所在房间
     * @param room
     */
    setRoom: function(room) {
        this._room = room;
    },

    /**
     * 坐位编号
     * @returns {number}
     */
    getIndex: function() {
        return this._index;
    },

    /**
     * 设置坐位编号
     * @param index
     */
    setIndex: function(index) {
        this._index = index;
    },

    /**
     * 发送数据
     * @param route
     * @param msg
     */
    send: function(route, msg) {
        if (this.isOnline()) {
            if (!this.isRobot()) {
                var uids = {uid: this._uid, sid:this._sid};
                logger.debug("room=%d index=%d send %s %j %j", this.getRoom().rid(), this.getIndex(), route, msg, uids);
                messageService.send(uids, route, msg);
            }
        } else {
            logger.debug("room=%d index=%d send %s %j", this.getRoom().rid(), this.getIndex(), route, msg);
        }
        this.executeAI(route, msg);
    },

    /**
     * 发送数据并保存战报
     * @param route
     * @param msg
     */
    sendReplay: function(route, msg) {
        this.send(route, msg);
        this.getRoom().addRoundReplay(route, msg);
    },

    /**
     * 设置在线状态
     * @param sid 前端服务器id
     */
    setOnline: function(sid) {
        if (this.isRobot()) {
            this._online = true;
            return;
        }

        if (sid) {
            this._online = true;
            this._sid = sid;
        } else {
            this._online = false;
            this._sid = null;
        }
    },

    /**
     * 是否在线
     * @returns {boolean}
     */
    isOnline: function() {
        return this._online;
    },

    /**
     * 设置准备状态
     * @param ready
     */
    setReady: function(ready) {
        this._ready = ready;
    },

    /**
     * 是否已准备
     * @returns {boolean}
     */
    isReady: function() {
        return this._ready;
    },

    /**
     * 设置是否正在游戏
     * @param playing
     */
    setPlaying: function(playing) {
        this._playing = playing;
    },

    /**
     * 是否正在游戏
     * @returns {boolean}
     */
    isPlaying: function() {
        return this._playing;
    },

    /**
     * 设置后台运行状态
     * @param b
     */
    setBackground: function (b) {
        this._background = b;
    },

    /**
     * 是否是在后台运行
     * @returns {boolean}
     */
    isBackground: function () {
        return this._background;
    },

    /**
     * 获取标志
     * @param key
     * @returns {*}
     */
    getMark: function(key) {
        return this._marks[key];
    },

    /**
     * 设置标志
     * @param key
     * @param value
     */
    setMark: function(key, value) {
        if (value) {
            this._marks[key] = value
        } else {
            delete this._marks[key];
        }
    },

    addRoundScore: function(score) {
        this._stat.roundScore += score;
        this._stat.score += score;
    },

    getScore: function() {
        return this._stat.score;
    },

    getRoundScore: function() {
        return this._stat.roundScore;
    },

    addRoundCoin: function(coin) {
        this._stat.roundCoin += coin;
    },

    getRoundCoin: function() {
        return this._stat.roundCoin;
    },

    getWaitHandleTime: function() {
        return this._waitHandleTime;
    },

    setWaitHandleTime: function(time) {
        this._waitHandleTime = time;

        if (!time) {
            if (this.isWaitTimeout()) {
                this.clearWaitTimeout();
                this.getRoom().broadcast("onPlayerClearWaitTimeout", {
                    playerIndex: this.getIndex(),
                });
            }
        }
    },

    isWaitTimeout: function() {
        return this._waitTimeoutTime != 0;
    },

    setWaitTimeout: function(handler, time) {
        clearTimeout(this._waitTimeoutTimer);
        this._waitTimeoutTime = this.getRoom().getNowTime();
        if (time) {
            this._waitTimeoutTimer = setTimeout(handler, time);
        } else {
            handler();
        }
    },

    clearWaitTimeout: function() {
        clearTimeout(this._waitTimeoutTimer);
        this._waitTimeoutTimer = 0;
        this._waitTimeoutTime = 0;
    },

    setTrustee: function(value) {
        if (value) {
            var LogicModule = this.getRoom().getLogicModule();
            if (!LogicModule.GameAI) {
                return;
            }
        }

        this._trustee = value;
    },

    getTrustee: function(value) {
        return this._trustee;
    },

    executeAI: function(route, msg) {
        if (!this.isRobot() && !this.getTrustee()) {
            return;
        }

        if (!this._ai) {
            var GameAI = this.getRoom().getLogicModule().GameAI;
            this._ai = new GameAI(this);
        }

        this._ai.execute(route, msg);
    },

    /******************************************************************
     * 需要重载的接口
     ******************************************************************/

    /**
     * 进入房间的个人信息
     */
    getInfo: function() {
        var info = {};

        info.name = this._user.name;
        info.headpic = this._user.headpic;
        info.sex = this._user.sex;
        info.coin = this._user.coin;
        info.gmLevel = this._user.gmLevel;
        info.ip = this._user.ip;

        info.gps = this._gps;

        info.uid = this._uid;
        info.online = this._online;
        info.ready = this._ready;
        info.playing = this._playing;
        info.background = this._background;

        info.matchInfo = this._user.matchInfo;

        return info;
    },

    /**
     * 断线重连时的个人信息
     */
    getReconnectInfo: function(isSelf) {
        var info = {};

        info.name = this._user.name;
        info.headpic = this._user.headpic;
        info.sex = this._user.sex;
        info.coin = this._user.coin;
        info.card = this._user.card;
        info.gmLevel = this._user.gmLevel;
        info.ip = this._user.ip;

        info.gps = this._gps;

        info.uid = this._uid;
        info.online = this._online;
        info.ready = this._ready;
        info.playing = this._playing;
        info.background = this._background;

        info.matchInfo = this._user.matchInfo;

        return info;
    },

    /**
     * 最终结算信息
     */
    getFinalReportInfo: function() {
        var info = {
            uid: this._uid,
            name: this._user.name,
            headpic: this._user.headpic,
            score: this._stat.score
        };

        if (this.getMark("forceQuit")) {
            info.forceQuit = 1;
        }

        return info;
    },

    getMatchResultInfo: function() {
        var info = {
            uid: this._uid,
            score: this._stat.score,
            roundScore: this.getRoundScore()
        };

        if (this.getMark("forceQuit")) {
            info.forceQuit = 1;
        }

        return info;
    },

    /**
     * 结算信息
     */
    getSettlementInfo: function() {
        var info = clone(this._stat);
        if (this.getRoom().isSceneRoom()) {
            info.coin = this.getResource("coin");
        }
        return info;
    },

    /**
     * 开始新一回合了
     */
    onStartNewRound: function() {
        this._stat.roundScore = 0;
        this._stat.roundCoin = 0;
    },

    /**
     * 当前回合结束了
     */
    onCurRoundFinished: function() {
        this.setWaitHandleTime(0);
        this.setTrustee(0);
    },

    /**
     * 回合结算处理
     */
    settlement: function() {
    }
});